<?php

namespace App\Http\Controllers\Admin;

use App\Models\Areas;
use App\Models\Category;
use App\Models\NewAdmin;
use App\Models\ShopRecharge;
use App\Models\ShopRechargeBoolea;
use App\Models\ShopRechargeRadar;
use App\Models\ShopRechargeEdu;
use App\Models\ShopRechargeCre;
use App\Models\ShopUser;
use App\Models\ShopUserLog;
use App\Services\CommonService;
use Illuminate\Http\Request;

//供应商列表
class SupplierController extends BaseController
{
    //供应商列表POST http://shop.cn:8004/Admin/Supplier/supplierList
    //{"page":1,"pageSize":10,"shopname":"","account_num":"","status":""}
    public function supplierList(Request $request)
    {
        $input = $request->input();
        $where = [];
        $where[] = ['su.is_delete', ShopUser::SHOP_USER_NOT_DELETE];
        if (!empty($input['shopname'])) {
            $where[] = ['su.shopname', 'like', '%' . trim($input['shopname']) . '%'];
        }
        if (!empty($input['account_num'])) {
            $where[] = ['oa.mobile', 'like', '%' . trim($input['account_num']) . '%'];
        }
        if (!empty($input['status'])) {
            $where[] = ['su.status', $input['status']];
        }
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = ShopUser::GetSupplierList($pageSize, $where);
        $data = formatPage($data);
        $info = $data['data'];
        foreach ($info as $k => $v) {
            $info[$k]['faptype_name'] = ShopUser::getFaptypeName($v['faptype']);//发票类型
            $info[$k]['status_name'] = ShopUser::getShopUserStatus($v['status']);//供应商审核状态
        }
        $data['data'] = $info;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //根据id查看供应商信息 http://shop.cn:8004/Admin/Supplier/supplierInfoById?id=208
    public function supplierInfoById(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        $shopUser = ShopUser::GetShopUser($where = array('id' => $input['id']));
        $category = Category::GetParentCateById($shopUser['category_id']);
        $shopcity = $shopUser['shopcity'];
        if (empty($shopcity)) {
            $shopcity_prov_id = '';
            $shopcity_city_id = '';
            $shopcity_area_id = '';
        } else {
            $shopcity = explode('-', $shopcity);
            $prov_data = !empty($shopcity[0]) ? Areas::GetAreasByName(array('name' => $shopcity[0])) : '';
            $city_data = !empty($shopcity[1]) ? Areas::GetAreasByName(array('name' => $shopcity[1])) : '';
            $area_data = !empty($shopcity[2]) && !empty($city_data['id']) ? Areas::GetAreasByName(array('name' => $shopcity[2], 'pid' => $city_data['id'])) : '';
            $shopcity_prov_id = !empty($prov_data['id']) ? $prov_data['id'] : '';
            $shopcity_city_id = !empty($city_data['id']) ? $city_data['id'] : '';
            $shopcity_area_id = !empty($area_data['id']) ? $area_data['id'] : '';
        }
        $company_area = $shopUser['company_area'];
        if (empty($company_area)) {
            $prov_id = '';
            $city_id = '';
            $area_id = '';
        } else {
            $company_area = explode('-', $company_area);
            $prov_data = !empty($company_area[0]) ? Areas::GetAreasByName(array('name' => $company_area[0])) : '';
            $city_data = !empty($company_area[1]) ? Areas::GetAreasByName(array('name' => $company_area[1])) : '';
            $area_data = !empty($company_area[2]) && !empty($city_data['id']) ? Areas::GetAreasByName(array('name' => $company_area[2], 'pid' => $city_data['id'])) : '';
            $prov_id = !empty($prov_data['id']) ? $prov_data['id'] : '';
            $city_id = !empty($city_data['id']) ? $city_data['id'] : '';
            $area_id = !empty($area_data['id']) ? $area_data['id'] : '';
        }
        $shopUserLog = ShopUserLog::GetLog(array('member_id' => $shopUser['member_id']));
        $operationRecord = array();
        foreach ($shopUserLog as $sulk => $sulv) {
            $arr["operation_content"] = $sulv['content'];
            $arr["operator"] = !empty($sulv['admin_id']) ? NewAdmin::GetNewAdminById($sulv['admin_id'])['username'] : $shopUser['contact_tel'];
            $arr["operation_time"] = $sulv['create_time'];
            $operationRecord[] = $arr;
        }
        $isMemberId = ShopRecharge::where(array('member_id' => $shopUser['member_id']))->value('member_id');
        if (empty($isMemberId)) {
            ShopRecharge::insert(array('member_id' => $shopUser['member_id'], 'risk_credit_automatic' => 2, 'risk_credit_amount' => 0));
        }
        $shopRecharge = ShopRecharge::where(array('member_id' => $shopUser['member_id']))->first();
        $shopRecharge = $shopRecharge ? $shopRecharge->toArray() : [];

        //布尔数据
        $isBooleaMemberId = ShopRechargeBoolea::where(array('member_id' => $shopUser['member_id']))->value('member_id');
        if (empty($isBooleaMemberId)) {
            ShopRechargeBoolea::insert(array('member_id' => $shopUser['member_id'], 'risk_credit_automatic' => 2, 'risk_credit_amount' => 0));
        }
        $shopRechargeBoolea = ShopRechargeBoolea::where(array('member_id' => $shopUser['member_id']))->first();
        $shopRechargeBoolea = $shopRechargeBoolea ? $shopRechargeBoolea->toArray() : [];

        //雷达数据
        $isRadarMemberId = ShopRechargeRadar::where(array('member_id' => $shopUser['member_id']))->value('member_id');
        if (empty($isRadarMemberId)) {
            ShopRechargeRadar::insert(array('member_id' => $shopUser['member_id'], 'risk_radar_automatic' => 2, 'risk_radar_amount' => 0));
        }
        $shopRechargeRadar = ShopRechargeRadar::where(array('member_id' => $shopUser['member_id']))->first();
        $shopRechargeRadar = $shopRechargeRadar ? $shopRechargeRadar->toArray() : [];


        //学历数据
        $isEduMemberId = ShopRechargeEdu::where(array('member_id' => $shopUser['member_id']))->value('member_id');
        if (empty($isEduMemberId)) {
            ShopRechargeEdu::insert(array('member_id' => $shopUser['member_id'], 'risk_edu_automatic' => 2, 'risk_edu_amount' => 0));
        }
        $shopRechargeRdu = ShopRechargeEdu::where(array('member_id' => $shopUser['member_id']))->first();
        $shopRechargeRdu = $shopRechargeRdu ? $shopRechargeRdu->toArray() : [];

        //征信数据
        $isCreMemberId = ShopRechargeCre::where(array('member_id' => $shopUser['member_id']))->value('member_id');
        if (empty($isCreMemberId)) {
            ShopRechargeCre::insert(array('member_id' => $shopUser['member_id'], 'risk_cre_automatic' => 2, 'risk_cre_amount' => 0));
        }
        $shopRechargeCre = ShopRechargeCre::where(array('member_id' => $shopUser['member_id']))->first();
        $shopRechargeCre = $shopRechargeCre ? $shopRechargeCre->toArray() : [];

        $data = array(
            'shopInfo' => array(
                'photo' => $shopUser['photo'], //店铺头像
                'shopname' => $shopUser['shopname'], //店铺名称
                'category_name' => isset($category['name']) ? $category['name'] : '', //经营项目
                'account' => $shopUser['account'],
                'account_name' => ShopUser::getAccountName($shopUser['account']),//账户类型
                'account_type' => $shopUser['account_type'],
                'account_type_name' => ShopUser::isAccountType($shopUser['account_type']),//是否风控
                'faptype' => $shopUser['faptype'],
                'faptype_name' => ShopUser::getFaptypeName($shopUser['faptype']),//发票类型
                'shopcity_prov_id' => $shopcity_prov_id,
                'shopcity_city_id' => $shopcity_city_id,
                'shopcity_area_id' => $shopcity_area_id,
                'shopcity' => $shopUser['shopcity'], //当前经营位置
                'people' => $shopUser['people'], //店铺联系人
                'contact_tel' => $shopUser['contact_tel'], //联系人手机
                'mobile' => $shopUser['mobile'], //客服电话
                'contract_type' => $shopUser['contract_type'],
                'contract_type_name' => ShopUser::getContractTypeName($shopUser['contract_type']),//签署合同类型
                'sign_num' => $shopUser['sign_num'],
                'sign_num_name' => ShopUser::getSignNumName($shopUser['sign_num']),//签署方式
                'is_city_location' => $shopUser['is_city_location'],
                'is_city_location_name' => ShopUser::isOpenOrClose($shopUser['is_city_location']),//是否开启城市定位  1开启  2关闭
                'email' => $shopUser['email'],//店铺邮箱
            ),
            'companyInfo' => array(
                'mechanism' => $shopUser['mechanism'], //公司名称
                'companyid' => $shopUser['companyid'], //工商注册号
                'prov_id' => $prov_id,
                'city_id' => $city_id,
                'area_id' => $area_id,
                'company_area' => $shopUser['company_area'], //公司所在区域
                'company' => $shopUser['company'], //公司地址
                'faname' => $shopUser['faname'], //法人姓名
                'idcard' => $shopUser['idcard'], //法人身份证号
                'shopcard' => $shopUser['shopcard'], //营业执照
                'doorphoto' => $shopUser['doorphoto'], //公司门头照
                'seal_url' => $shopUser['seal_url'], //公章图片
                'faidcard' => $shopUser['faidcard'], //身份证正面照
                'faidcard_back' => $shopUser['faidcard_back'], //身份证反面照
                'esign_seal_id' => $shopUser['esign_seal_id'], //E签宝印章id
            ),
            'operationRecord' => $operationRecord,
            'withdrawInfo' => array(
                'payeename' => $shopUser['payeename'], //支付宝姓名
                'alipayaccount' => $shopUser['alipayaccount'], //支付宝账号
            ),
            'incrementInfo' => array(
                'sms_num' => $shopUser['sms_num'], //短信剩余数量
                'is_guarantee' => $shopUser['is_guarantee'],
                'is_guarantee_name' => ShopUser::isGuarantee($shopUser['is_guarantee']),//是否开启担保合同 0关闭1开启
                'set_lease_days' => $shopUser['set_lease_days'], //是否设置租赁周期的权限 1是 2否
                'guarantee_amount' => $shopUser['guarantee_amount'], //担保金额
                'guarantee_minage' => $shopUser['guarantee_minage'], //年龄范围-担保年龄下限
                'guarantee_maxage' => $shopUser['guarantee_maxage'], //年龄范围-担保年龄上限
                'mutual_guarantee' => $shopUser['mutual_guarantee'],
                'mutual_guarantee_name' => ShopUser::isMutualGuarantee($shopUser['mutual_guarantee']),//是否允许互相担保  0禁止  1允许
                'contract_num' => $shopUser['contract_num'], //合同剩余数量
                'risk_credit_status' => $shopRecharge['risk_credit_status'], //百融风控状态   1开启  2关闭
                'risk_credit_amount' => $shopRecharge['risk_credit_amount'], //百融风控剩余查询次数
                'risk_credit_status_boolea' => $shopRechargeBoolea['risk_credit_status'], //布尔数据状态   1开启  2关闭
                'risk_credit_amount_boolea' => $shopRechargeBoolea['risk_credit_amount'], //布尔数据剩余查询次数
                'risk_radar_status_credit' => $shopRechargeRadar['risk_radar_status'], //雷达数据状态   1开启  2关闭
                'risk_radar_amount_credit' => $shopRechargeRadar['risk_radar_amount'], //雷达数据剩余查询次数
                'risk_edu_status_credit' => $shopRechargeRdu['risk_edu_status'], //学历数据状态   1开启  2关闭
                'risk_edu_amount_credit' => $shopRechargeRdu['risk_edu_amount'], //学历数据剩余查询次数
                'risk_cre_status' => $shopRechargeCre['risk_cre_status'], //学历数据状态   1开启  2关闭
                'risk_cre_amount' => $shopRechargeCre['risk_cre_amount'], //学历数据剩余查询次数
            ),
            'functionSetInfo' => array(
                'report_bill' => $shopUser['report_bill'], //线下报单融资功能  1开启 2关闭
                'ant_shield_risk_score' => $shopUser['ant_shield_risk_score'], //蚁盾风控分数
                'is_automatic_report_bill' => $shopUser['is_automatic_report_bill'], //是否开启自动报单同步  1开启 2关闭
            ),
        );
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //获取经营项目 http://shop.cn:8004/Admin/Supplier/getCategoryName
    public function getCategoryName()
    {
        $data = Category::GetParentCate();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //根据id编辑供应商信息
    public function editSupplierById(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        if (count($input) == 2) { //编辑是否启用禁用
            $select = array('member_id', 'id', 'endisable');
            $shopUser = ShopUser::select($select)->where(array('id' => $input['id']))->first();
            $shopUser = $shopUser ? $shopUser->toArray() : array();
            $member_id = $shopUser['member_id'];
            unset($shopUser['member_id']);
        } else {
            $select = array('su.member_id', 'su.id', 'su.photo', 'su.shopname', 'su.account', 'su.account_type', 'su.faptype', 'su.shopcity', 'su.people', 'su.contact_tel', 'su.mobile',
                'su.contract_type', 'su.sign_num', 'su.is_city_location',
                'su.mechanism', 'su.companyid', 'su.company_area', 'su.company', 'su.faname', 'su.idcard', 'su.shopcard', 'su.doorphoto', 'su.seal_url', 'su.faidcard', 'su.faidcard_back',
                'su.payeename', 'su.alipayaccount', 'su.sms_num', 'su.is_guarantee', 'su.guarantee_amount', 'su.guarantee_minage', 'su.guarantee_maxage', 'su.mutual_guarantee', 'su.contract_num',
                'su.report_bill', 'su.ant_shield_risk_score', 'su.is_automatic_report_bill', 'su.email', 'sr.risk_credit_status', 'sr.risk_credit_amount', 'sc.risk_cre_status', 'sc.risk_cre_amount', 'su.esign_seal_id');
            $shopUser = ShopUser::from('sp_shop_user_2 as su')
                ->leftjoin('sp_shop_recharge as sr', 'sr.member_id', 'su.member_id')
                ->leftjoin('sp_shop_recharge_credit as sc', 'sc.member_id', 'su.member_id')
                ->select($select)
                ->where(array('su.id' => $input['id']))
                ->first();
            $shopUser = $shopUser ? $shopUser->toArray() : array();
            $member_id = $shopUser['member_id'];
            unset($shopUser['member_id']);
        }
        $before_data = array_diff_assoc($shopUser, $input);
        $after_data = array_diff_assoc($input, $shopUser);
        if (empty($before_data)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据未发生变化');
        }
        if (array_key_exists('contact_tel', $input)) {
            if (!Verify_Phone($input['contact_tel'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效联系人手机号');
            }
        }
        if (array_key_exists('mobile', $input)) {
            if (!isTel($input['mobile'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效客服电话');
            }
        }
        if (array_key_exists('companyid', $input)) {
            if (!isBusinessRegistrationNumber($input['companyid'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效工商注册号');
            }
        }
        if (array_key_exists('idcard', $input)) {
            if (!check_passportid($input['idcard'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效法人身份证号');
            }
        }
        if (array_key_exists('alipayaccount', $input)) {
            if (!empty($input['alipayaccount'])) {
                if (!check_alipayaccount($input['alipayaccount'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效支付宝账号');
                }
            }
        }
        if (array_key_exists('email', $input)) {
            if (!empty($input['email'])) {
                if (!check_email($input['email'])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效店铺邮箱');
                }
            }
        }
        if (array_key_exists('endisable', $input)) {
            if ($input['endisable'] == ShopUser::SHOP_USER_DISABLE) { //是否启用：1 启用  2禁用
                NewAdmin::editNewAdmin(array('type' => NewAdmin::OTHER_ADMIN_TYPE_SHOPER, 'user_id' => $member_id), array('status' => NewAdmin::OTHER_ADMIN_STATUS_DISABLE));
            } elseif ($input['endisable'] == ShopUser::SHOP_USER_ENABLE) {
                NewAdmin::editNewAdmin(array('type' => NewAdmin::OTHER_ADMIN_TYPE_SHOPER, 'user_id' => $member_id), array('status' => NewAdmin::OTHER_ADMIN_STATUS_ENABLE));
            }
        }
        $editShopUserData = $after_data;
        if (array_key_exists('risk_credit_status', $after_data)) {
            unset($editShopUserData['risk_credit_status']);
            ShopRecharge::where(array('member_id' => $member_id))->update(array('risk_credit_status' => $after_data['risk_credit_status']));
        }
        if (array_key_exists('risk_credit_amount', $after_data)) {
            unset($editShopUserData['risk_credit_amount']);
            ShopRecharge::where(array('member_id' => $member_id))->update(array('risk_credit_amount' => $after_data['risk_credit_amount']));
        }

        //修改布尔数据
        if (array_key_exists('risk_credit_status_boolea', $after_data)) {
            unset($editShopUserData['risk_credit_status_boolea']);
            ShopRechargeBoolea::where(array('member_id' => $member_id))->update(array('risk_credit_status' => $after_data['risk_credit_status_boolea']));
        }
        if (array_key_exists('risk_credit_amount_boolea', $after_data)) {
            unset($editShopUserData['risk_credit_amount_boolea']);
            ShopRechargeBoolea::where(array('member_id' => $member_id))->update(array('risk_credit_amount' => $after_data['risk_credit_amount_boolea']));
        }

        //修改雷达数据
        if (array_key_exists('risk_radar_status_credit', $after_data)) {
            unset($editShopUserData['risk_radar_status_credit']);
            ShopRechargeRadar::where(array('member_id' => $member_id))->update(array('risk_radar_status' => $after_data['risk_radar_status_credit']));
        }
        if (array_key_exists('risk_radar_amount_credit', $after_data)) {
            unset($editShopUserData['risk_radar_amount_credit']);
            ShopRechargeRadar::where(array('member_id' => $member_id))->update(array('risk_radar_amount' => $after_data['risk_radar_amount_credit']));
        }

        //修改学历数据
        if (array_key_exists('risk_edu_status_credit', $after_data)) {
            unset($editShopUserData['risk_edu_status_credit']);
            ShopRechargeEdu::where(array('member_id' => $member_id))->update(array('risk_edu_status' => $after_data['risk_edu_status_credit']));
        }
        if (array_key_exists('risk_edu_amount_credit', $after_data)) {
            unset($editShopUserData['risk_edu_amount_credit']);
            ShopRechargeEdu::where(array('member_id' => $member_id))->update(array('risk_edu_amount' => $after_data['risk_edu_amount_credit']));
        }
        //修改征信数据
        if (array_key_exists('risk_cre_status', $after_data)) {
            unset($editShopUserData['risk_cre_status']);
            ShopRechargeCre::where(array('member_id' => $member_id))->update(array('risk_cre_status' => $after_data['risk_cre_status']));
        }
        if (array_key_exists('risk_cre_amount', $after_data)) {
            unset($editShopUserData['risk_cre_amount']);
            ShopRechargeCre::where(array('member_id' => $member_id))->update(array('risk_cre_amount' => $after_data['risk_cre_amount']));
        }

        if (!empty($editShopUserData)) {
            ShopUser::editShopUserByid($input['id'], $editShopUserData);
        }
        //添加操作记录
        ShopUserLog::addLog($this->users['id'], $member_id, 1, '编辑供应商', $before_data, $after_data, '');
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功');
    }


}
